import router from "@/router";
import { useUserStore } from "@/stores";
import ACCESS_ENUM from "@/access/ACCESS_ENUM";
import checkAccess from "@/access/checkAccess";
import message from "@arco-design/web-vue/es/message";

//全局权限拦截跳转
router.beforeEach(async (to, from, next) => {
  if (to.path === "/login") {
    next();
  }

  const userStore = useUserStore();
  let currentUser = userStore.userInfo;
  console.log(
    `当前登录用户名:${currentUser.username},权限:${currentUser.role}`
  );
  //如果之前没登录过,自动登录
  if (
    !currentUser ||
    currentUser.role === ACCESS_ENUM.NO_LOGIN ||
    currentUser === {}
  ) {
    currentUser = await userStore.getLoginUser();
    console.log("正在尝试自动登录...", currentUser);
  }

  const needAccess = (to?.meta?.access ?? ACCESS_ENUM.NO_LOGIN) as string;

  //需要跳转的页面,必须登录
  if (needAccess !== ACCESS_ENUM.NO_LOGIN) {
    console.log(to.path + "页面需要的权限:", needAccess);
    //如果没登录,跳转到登录页面
    if (!currentUser || currentUser.role === ACCESS_ENUM.NO_LOGIN) {
      message.warning("请登录");
      next("/login");
      return;
    }
    //如果登录过,但是权限不足,那么跳转到无权限页面
    if (!checkAccess(currentUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
